﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace Epam.PeopleModel
{
    public class DateRangeAttribute:ValidationAttribute,IClientValidatable,IMetadataAware
    {
        public string MinDate { get; set; }

        public override bool IsValid(object value)
        {
            if (value == null) return true;
            var date = (DateTime)value;
            return date <= DateTime.Now && date >=DateTime.Parse(MinDate);
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessage,
                ValidationType = "rangedatevalidation"
            };
            rule.ValidationParameters["mindate"] = MinDate;
            rule.ValidationParameters["maxdate"] = DateTime.Now.ToString("dd/MM/yyyy");
            yield return rule;
        }

        public void OnMetadataCreated(ModelMetadata metadata)
        {
            metadata.DataTypeName = "Date";
        }
    }
}
